<template>
	<div 
		ref="lottieContainer" 
		:style="containerStyle"
		class="lottie-container"
	></div>
</template>

<script>
import lottie from 'lottie-web';

export default {
	name: 'LottieAnimation',
	props: {
		animationData: {
			type: Object,
			required: true
		},
		width: {
			type: [String, Number],
			default: '100%'
		},
		height: {
			type: [String, Number],
			default: '100%'
		},
		autoplay: {
			type: Boolean,
			default: true
		},
		loop: {
			type: Boolean,
			default: true
		},
		speed: {
			type: Number,
			default: 1
		}
	},
	data() {
		return {
			animation: null
		};
	},
	computed: {
		containerStyle() {
			return {
				width: typeof this.width === 'number' ? `${this.width}px` : this.width,
				height: typeof this.height === 'number' ? `${this.height}px` : this.height
			};
		}
	},
	mounted() {
		this.initAnimation();
	},
	beforeDestroy() {
		if (this.animation) {
			this.animation.destroy();
			this.animation = null;
		}
	},
	watch: {
		animationData: {
			handler() {
				this.initAnimation();
			},
			deep: true
		}
	},
	methods: {
		initAnimation() {
			if (this.animation) {
				this.animation.destroy();
			}

			this.animation = lottie.loadAnimation({
				container: this.$refs.lottieContainer,
				renderer: 'svg',
				loop: this.loop,
				autoplay: this.autoplay,
				animationData: this.animationData
			});

			this.animation.setSpeed(this.speed);

			// 触发事件
			this.animation.addEventListener('complete', () => {
				this.$emit('complete');
			});

			this.animation.addEventListener('loopComplete', () => {
				this.$emit('loopComplete');
			});

			this.$emit('ready', this.animation);
		},
		play() {
			if (this.animation) {
				this.animation.play();
			}
		},
		pause() {
			if (this.animation) {
				this.animation.pause();
			}
		},
		stop() {
			if (this.animation) {
				this.animation.stop();
			}
		},
		setSpeed(speed) {
			if (this.animation) {
				this.animation.setSpeed(speed);
			}
		}
	}
};
</script>

<style scoped>
.lottie-container {
	display: inline-block;
}
</style>